﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using NConf.Libraries;

namespace NConf.ConfigSources
{
    public class INIConfigSource : DictConfigSource
    {
        //---------------------------------------------------------------------

        #region Internal Members

        /// <summary>
        /// The ini file parser instance.
        /// </summary>
        private IniFile iniFile;

        /// <summary>
        /// A Read/Write thread lock
        /// </summary>
        private ReaderWriterLockSlim confLock = new ReaderWriterLockSlim();

        #endregion

        //---------------------------------------------------------------------

        #region Constructors

        /// <summary>
        /// Default Constructor.
        /// </summary>
        public INIConfigSource(string filename) : base()
        {
            // Populate the iniFile
            iniFile = new IniFile(filename);

            // Load the configuration database.
            ParseIniDict();
        } // end DummyConfigSource

        #endregion

        //---------------------------------------------------------------------

        #region Internal Helpers

        private void ParseIniDict()
        {
            var iniDict = iniFile.ToDictionary();
            Configuration.Clear();

            foreach (var section in iniDict)
            {
                foreach (var kvp in section.Value)
                {
                    SetValue(section.Key + "." + kvp.Key, kvp.Value);
                } // end foreach
            } // end foreach
        } // end ParseIniDict

        #endregion

        //---------------------------------------------------------------------
    } // end INIConfigSource
} // end NConf.ConfigSources namespace
